<template>
  <view class="music-player">
    <!-- 顶部导航栏 -->
    <tn-nav-bar fixed alpha>
      <view slot="back" class='nav-back'>
        <text class="tn-icon-left"></text>
        <text class="nav-back-title">返回</text>
      </view>
      <view slot="content" class="nav-title">音乐播放器</view>
    </tn-nav-bar>
    
    <!-- 封面区域 -->
    <view class="cover-container">
      <image class="music-cover" :class="{ 'rotate': isPlaying }" src="/static/music-cover.png" mode="aspectFill"></image>
    </view>
    
    <!-- 音乐信息 -->
    <view class="music-info">
      <text class="song-name">歌曲名称</text>
      <text class="artist-name">歌手名称</text>
    </view>
    
    <!-- 进度条 -->
    <view class="progress-bar">
      <text class="time-text">{{currentTime}}</text>
      <tn-slider
        v-model="progress"
        @change="onProgressChange"
        activeColor="#8C67E6"
        backgroundColor="#E6E6E6"
        block-size="12"
      ></tn-slider>
      <text class="time-text">{{duration}}</text>
    </view>
    
    <!-- 控制按钮 -->
    <view class="control-buttons">
      <view class="btn-item" @click="prevSong">
        <text class="tn-icon-previous"></text>
      </view>
      <view class="btn-item play-btn" @click="togglePlay">
        <text :class="isPlaying ? 'tn-icon-pause' : 'tn-icon-play'"></text>
      </view>
      <view class="btn-item" @click="nextSong">
        <text class="tn-icon-next"></text>
      </view>
      <view class="btn-item" @click="togglePlayMode">
        <text :class="playMode === 'loop' ? 'tn-icon-loop' : 'tn-icon-sequence'"></text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isPlaying: false,
      progress: 0,
      currentTime: '00:00',
      duration: '00:00',
      audioContext: null,
      playMode: 'sequence', // 播放模式：sequence-顺序播放，loop-单曲循环
      currentSongIndex: 0, // 当前播放歌曲的索引
      playlist: [], // 播放列表
      playlistConfig: null // 播放列表配置
    }
  },
  methods: {
    // 切换播放状态
    togglePlay() {
      if (!this.audioContext || !this.playlist.length) return
      
      if (this.isPlaying) {
        this.audioContext.pause()
      } else {
        this.audioContext.play()
      }
      this.isPlaying = !this.isPlaying
    },
    // 上一首
    prevSong() {
      if (!this.playlist.length) return
      
      this.currentSongIndex = this.currentSongIndex > 0 ? 
        this.currentSongIndex - 1 : 
        this.playlist.length - 1
      
      this.playSong(this.currentSongIndex)
    },
    // 下一首
    nextSong() {
      if (!this.playlist.length) return
      
      this.currentSongIndex = this.currentSongIndex < this.playlist.length - 1 ? 
        this.currentSongIndex + 1 : 
        0
      
      this.playSong(this.currentSongIndex)
    },
    // 播放指定索引的歌曲
    playSong(index) {
      if (!this.playlist[index]) return
      
      const song = this.playlist[index]
      
      // 如果已经创建了音频上下文，先销毁它
      if (this.audioContext) {
        this.audioContext.destroy()
      }
      
      // 创建新的音频上下文
      this.audioContext = uni.createInnerAudioContext()
      this.audioContext.src = song.url
      
      // 重新绑定事件
      this.bindAudioEvents()
      
      // 自动播放
      this.audioContext.play()
      this.isPlaying = true
    },
    // 绑定音频事件
    bindAudioEvents() {
      this.audioContext.onEnded(() => {
        if (this.playMode === 'loop') {
          // 单曲循环模式：重新播放当前歌曲
          this.audioContext.seek(0)
          this.audioContext.play()
        } else {
          // 顺序播放模式：播放下一首
          this.nextSong()
        }
      })
      
      this.audioContext.onTimeUpdate(() => {
        this.currentTime = this.formatTime(this.audioContext.currentTime)
        this.duration = this.formatTime(this.audioContext.duration)
        this.progress = (this.audioContext.currentTime / this.audioContext.duration) * 100
      })
      
      this.audioContext.onError((res) => {
        console.error('音频播放错误：', res.errMsg)
        uni.showToast({
          title: '音频播放出错',
          icon: 'none'
        })
      })
    },
    // 进度条改变
    onProgressChange(value) {
      if (!this.audioContext) return
      
      const seekTime = (value / 100) * this.audioContext.duration
      this.audioContext.seek(seekTime)
      this.progress = value
    },
    // 格式化时间
    formatTime(time) {
      const minutes = Math.floor(time / 60)
      const seconds = Math.floor(time % 60)
      return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
    },
    
    // 切换播放模式
    togglePlayMode() {
      this.playMode = this.playMode === 'sequence' ? 'loop' : 'sequence'
    },
    
    onLoad() {
      // 加载播放列表配置
      uni.request({
        url: '/static/music/playlist.json',
        success: (res) => {
          this.playlistConfig = res.data
          this.playlist = this.playlistConfig.playlist
          if (this.playlist.length > 0) {
            // 初始化第一首歌
            const firstSong = this.playlist[0]
            this.audioContext = uni.createInnerAudioContext()
            this.audioContext.src = firstSong.url
          }
        }
      })
      
      // 初始化音频上下文
      this.audioContext = uni.createInnerAudioContext()
      
      // 添加音频事件监听
      this.audioContext.onEnded(() => {
        if (this.playMode === 'loop') {
          // 单曲循环模式：重新播放当前歌曲
          this.audioContext.seek(0)
          this.audioContext.play()
        } else {
          // 顺序播放模式：播放下一首
          this.nextSong()
        }
      })
      
      // 监听播放进度
      this.audioContext.onTimeUpdate(() => {
        this.currentTime = this.formatTime(this.audioContext.currentTime)
        this.duration = this.formatTime(this.audioContext.duration)
        this.progress = (this.audioContext.currentTime / this.audioContext.duration) * 100
      })
    },
  },
  onUnload() {
    // 销毁音频上下文
    if (this.audioContext) {
      this.audioContext.destroy()
    }
  }
}
</script>

<style lang="scss" scoped>
.music-player {
  min-height: 100vh;
  background: linear-gradient(to bottom, #8C67E6, #6C5CE7);
  padding-top: 88rpx;
  
  .nav-back {
    display: flex;
    align-items: center;
    color: #FFFFFF;
    font-size: 28rpx;
    
    .tn-icon-left {
      margin-right: 4rpx;
    }
  }
  
  .nav-title {
    color: #FFFFFF;
    font-size: 32rpx;
  }
  
  .cover-container {
    display: flex;
    justify-content: center;
    margin-top: 60rpx;
    
    .music-cover {
      width: 500rpx;
      height: 500rpx;
      border-radius: 50%;
      box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.2);
      
      &.rotate {
        animation: rotate 20s linear infinite;
      }
    }
  }
  
  .music-info {
    text-align: center;
    margin-top: 40rpx;
    
    .song-name {
      display: block;
      color: #FFFFFF;
      font-size: 36rpx;
      font-weight: bold;
      margin-bottom: 10rpx;
    }
    
    .artist-name {
      display: block;
      color: rgba(255, 255, 255, 0.8);
      font-size: 28rpx;
    }
  }
  
  .progress-bar {
    margin: 60rpx 40rpx;
    display: flex;
    align-items: center;
    
    .time-text {
      color: rgba(255, 255, 255, 0.8);
      font-size: 24rpx;
      width: 80rpx;
    }
    
    .tn-slider {
      flex: 1;
      margin: 0 20rpx;
    }
  }
  
  .control-buttons {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 40rpx;
    
    .btn-item {
      width: 80rpx;
      height: 80rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 0 30rpx;
      
      text {
        color: #FFFFFF;
        font-size: 40rpx;
      }
      
      &.play-btn {
        width: 100rpx;
        height: 100rpx;
        background: rgba(255, 255, 255, 0.2);
        border-radius: 50%;
        
        text {
          font-size: 50rpx;
        }
      }
    }
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>